import {messages} from "share/common";
/**
 * Created by zhouli on 2019/2/27
 */
/*
* 需后端修改响应类型
* 不返回 JSON
* 改法：参考接口 http://192.168.10.31:8002/api/upload/attachment/v2, 目前已经上dev
* todo 需要把上传附件的接口，都找出来，后端修改
* */
import React from 'react';
import config from 'config'
import Upload from 'rc-upload';
import { Icon, Button, message } from 'antd';

import 'styles/components/template/ie-file-upload/file-upload.scss'
import errorMessage from "share/errorMessage";

class FileUpload extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      fileName: "",
      loading: false,
    }
  }
  render() {
    const that = this;
    const uploaderProps = {
      action: this.props.uploadUrl,
      data: {
        access_token: this.props.token,
        ...that.props.data
      },
      //ie下不支持设置 header
      //https://github.com/react-component/upload/issues/22
      headers: {},
      multiple: true,
      disabled: that.props.disabled,
      accept: that.props.accept,
      beforeUpload(file) {
        if (that.props.beforeUpload(file)) {
          that.setState({
            fileName: file.name
          });
          return true;
        } else {
          return false;
        }
      },
      onStart: (file) => {
        that.setState({
          loading: true,
        })
      },
      onSuccess(file) {
        let res = file;
        try {
          //ie
          res = JSON.parse(file)
        } catch (e) {
          res = file;
        }
        for (let key in res) {
          if (res[key] && res[key].replace) {
            res[key] = res[key].replace(/&amp;/g, '&');
          }
        }
        that.setState({
          loading: false,
        });

        that.props.onChange(res);
      },
      onProgress(step, file) {
        that.setState({
          loading: true,
        });
        console.log('onProgress', Math.round(step.percent), file.name);
      },
      onError(err, note) {
        that.setState({
          loading: false,
        });
        if(note){
          message.error(note.message || 'error');
        }
      },
    };
    const {fileName, loading} = this.state;
    return (
      <div className="file-upload-wrap">
        <div className="file-name">{fileName}</div>
        <Upload {...uploaderProps}>
          <Button disabled={this.props.disabled} loading={loading} className="file-upload-button">
            <Icon type="upload"/> {messages('components.key492')/*上传文件*/}
          </Button>
        </Upload>
      </div>
    );
  }
}

FileUpload.propTypes = {
  data: React.PropTypes.any,
  token: React.PropTypes.any,
  beforeUpload: React.PropTypes.func,//上传之前检测，返回false不上传
  uploadUrl: React.PropTypes.string,  //上传URL
  onChange: React.PropTypes.func,  //上传成功后的回调
  disabled: React.PropTypes.any,
};
FileUpload.defaultProps = {
  data:{},
  uploadUrl: `${config.baseUrl}/api/upload/attachment/v2`,
  beforeUpload: () => true,
  disabled:false,
};

export default FileUpload;

